package com.atguigu.flink.chapter07.state;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.util.Collector;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

import static org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION;
import static org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer.Semantic.EXACTLY_ONCE;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/1/18 9:19
 */
public class Flink09_Kafka_Flink_Kafka {
    public static void main(String[] args) throws IOException {
        System.setProperty("HADOOP_USER_NAME", "atguigu");
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        env.enableCheckpointing(3000);// checkpoint周期
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop162:8020/ck20");
        
        // 设置 checkpoint的模式: 至少一次(barrier不对齐)或者严格变一次(barrier对齐)
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
        // 同时允许最大checkpoint的数量
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
        // 当取消 job, 是否把checkpoint数据继续保留下来
        env.getCheckpointConfig().enableExternalizedCheckpoints(RETAIN_ON_CANCELLATION);
        // checkpoint 超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000);
        
        Properties sourceProps = new Properties();
        sourceProps.setProperty("bootstrap.servers", "hadoop162:9092");
        sourceProps.setProperty("group.id", "Flink09_Kafka_Flink_Kafka2");
        sourceProps.setProperty("auto.reset.offset", "latest"); // 如果没有消费记录, 从最新的位置开始消费. 如果有上次的消费记录, 则从上次的位置开始消费
        sourceProps.setProperty("isolation.level", "read_committed"); // 只读取别人已经提交的数据, 防止重复消费
        
        
        Properties sinkProps = new Properties();
        sinkProps.setProperty("bootstrap.servers", "hadoop162:9092");
        sinkProps.setProperty("transaction.timeout.ms", 15 * 60 * 1000 + "");
        
        
        SingleOutputStreamOperator<Tuple2<String, Long>> resultStream = env
            .addSource(new FlinkKafkaConsumer<String>("s1", new SimpleStringSchema(), sourceProps))
            .flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
                
                @Override
                public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                    for (String word : value.split(" ")) {
                        out.collect(Tuple2.of(word, 1L));
                    }
                }
            })
            .keyBy(t -> t.f0)
            .sum(1);
        
        resultStream.addSink(new FlinkKafkaProducer<Tuple2<String, Long>>(
            "default",
            new KafkaSerializationSchema<Tuple2<String, Long>>() {
                @Override
                public ProducerRecord<byte[], byte[]> serialize(Tuple2<String, Long> element,
                                                                @Nullable Long timestamp) {
                    return new ProducerRecord<>("s2", (element.f0 + "_" + element.f1).getBytes(StandardCharsets.UTF_8));
                }
            },
            sinkProps,
            EXACTLY_ONCE  // 开启事务
        ));
    
        resultStream.addSink(new SinkFunction<Tuple2<String, Long>>() {
            @Override
            public void invoke(Tuple2<String, Long> value,
                               Context context) throws Exception {
                if (value.f0.contains("x")) {
                    throw new RuntimeException("碰到了x, 抛异常");
                }
            }
        });
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

